package com.alongthink.javademo.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 接收redis信息，当redis推送了数据，该方法会自动出队
 */
@Slf4j
@Component
public class Receiver implements MessageListener {
//    public static ByteBuffer byteBuffer1 = ByteBuffer.allocateDirect(1024*1024*10);//存储文件的大小10M
    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer serializer = new ByteRedisSerializer();
        byte[] bytes = (byte[]) serializer.deserialize(message.getBody());
        try {
            long endTime2 = System.currentTimeMillis();
            //process data

//            int pos = Receiver.byteBuffer1.position();
//            int lim = Receiver.byteBuffer1.limit();
//            int mul = lim - pos;
//            if (mul < bytes.length) {
//                //放不下了,把原有数据写入到文件，并重置容器，再写入数据
//                Date date = new Date();
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss_sss");
//                String fileName = simpleDateFormat.format(date) + ".bin";
//                ByteBuffer byteBuffer = ByteBuffer.allocate(Receiver.fileSize);
//                Receiver.byteBuffer1.flip();
//                byteBuffer.put(Receiver.byteBuffer1);
//                Receiver.writeFileThreadPool.execute(new ThreadWriteFile(fileName, byteBuffer));
//
//                Receiver.byteBuffer1.position(0);//.rewind();//复位position的值为0
//                Receiver.byteBuffer1.limit(InitApplicationRunner.fileSize);
//                Receiver.byteBuffer1.put(bytes);
//            } else {
//                //容量足够
//                Receiver.byteBuffer1.put(bytes);
//            }
            long endTime4 = System.currentTimeMillis();
            log.info("redis接收消息,用时：" + (endTime4 - endTime2) + "ms");
        }catch (Exception e){
            log.warn("redis接收消息异常，"+e.getMessage());
        }
    }
}
